package com.atsmart.app.sql;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import com.atsmart.app.model.PositionInfo;

public class PositionHistorySqlHelper {

	private SQLiteDatabase db = null;

	/**
	 * 打开数据库
	 */
	public void open(SqlHelper dh) {
		// dh = new SqlHelper(null, "atsmart", null,SqlHelper.getDBVersion());
		db = dh.getWritableDatabase();
	}

	public synchronized void addPositionHistory(PositionInfo at) {
		if (at == null) {
			return;
		}
		String strSql = "insert or replace into position_history_info (type,msgType,lon,lat,date) values(?,?,?,?,?);";
		try {
			SQLiteStatement stm = db.compileStatement(strSql);
			stm.bindLong(1, at.type);
			stm.bindLong(2, at.msgType);
			stm.bindDouble(3, at.lon);
			stm.bindDouble(4, at.lat);
			stm.bindString(5, at.date);
			stm.bindString(6, at.locationMsg);
			stm.execute();
			stm.clearBindings();
			stm.close();
		} catch (Exception e) {
			e.printStackTrace();
			// will not happen
		}
	}

	public List<PositionInfo> getAttribute() {
		String sql = " select _id,type,msgType,lon,lat,date from position_history_info";
		Cursor cursor = db.rawQuery(sql, null);
		PositionInfo historie = null;
		List<PositionInfo> pos = null;
		try {
			if (cursor != null && cursor.moveToFirst()) {
				pos = new ArrayList<PositionInfo>();
				for (int i = 0; i < cursor.getCount(); i++) {
				historie = new PositionInfo();
				historie.type = cursor.getInt(1);
				historie.msgType = cursor.getInt(2);
				historie.lon = cursor.getDouble(3);
				historie.lat = cursor.getDouble(4);
				historie.date = cursor.getString(5);
				historie.locationMsg = cursor.getString(6);
				pos.add(historie);
				cursor.moveToNext();
			}
			}
		} catch (Exception e) {
			return null;
		} finally {
			cursor.close();
		}
		return pos;
	}

	public void deleteAttribute() {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from position_history_info");
	}
}
